import json
from django import http
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from apps.goods.models import SKU
from utils.cookiesecret import CookieSecret
from utils.response_code import RETCODE

# 购物车管理
class CartsView(View):
    # 展示购物车界面
    def get(self,request):
        user = request.user
        if user.is_authenticated:
            # 登录从redis取数据
            client = get_redis_connection("carts")
            carts_redis = client.hgetall(user.id)
            carts_dict = {}
            # 遍历redis取出的字节  将字节形式的字典转换成字符串形式的字典
            for key,value in carts_redis.items():
                cart_key = int(key.decode())
                cate_redis_dict = json.loads(value.decode())
                carts_dict[cart_key] = cate_redis_dict
                # 字典推倒式
        else:
            cookie_str = request.COOKIES.get("carts")
            if cookie_str:
                # 解密
                carts_dict = CookieSecret.loads(cookie_str)
            else:
                carts_dict = {}
        sku_ids = carts_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus=[]
        # 前端没有小数格式
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': carts_dict.get(sku.id).get('count'),
                'selected': str(carts_dict.get(sku.id).get('selected')),  # 将True，转'True'，方便json解析
                'default_image_url': sku.default_image.url,
                'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'amount': str(sku.price * carts_dict.get(sku.id).get('count')),
            })
        context = {
            'cart_skus': cart_skus,
        }
            # 渲染购物车页面
        return render(request, 'cart.html', context)
    # 添加购物车
    def post(self, request):
        """添加购物车"""
        # 接收和校验参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get("sku_id")
        count = json_dict.get("count")
        # 添加默认选中
        selected = json_dict.get("selected",True)
        # 校验# sku_id是否存在
        try:
            #如果没有值get会报错
            SKU.objects.get(id=sku_id)
        except:
            return http.HttpResponseForbidden("商品不存在")
        # 判断整数
        try:
            # 强行转成整形如果报错则数据类型有问题
            count = int(count)
        except:
            return http.HttpResponseForbidden("count不是整形")
        if selected:
            # 判断是不是布尔类型
            if not isinstance(selected,bool):
                return http.HttpResponseForbidden("selected不是布尔类型")
        # 判断用户是否登录
        user = request.user
        response = JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
        if user.is_authenticated:
            # 用户已登录，操作redis购物车
            # 配置redis5号库
            # 链接redis
            redis_carts_client = get_redis_connection("carts")
            client_data = redis_carts_client.hgetall(user.id)
            # print(client_data)
            # redis返回的所有数据都是字节  int转字节  先转字符串后encode
            if str(sku_id).encode() in client_data:
                bytes_carts = client_data[str(sku_id).encode()]
                # print(bytes_carts)
                str_carts = bytes_carts.decode()
                dict_carts = json.loads(str_carts)
                dict_carts["count"] += count
                redis_carts_client.hset(user.id,sku_id,json.dumps(dict_carts))
            else:
                redis_carts_client.hset(user.id,sku_id,json.dumps({"count":count,'selected':selected}))
            # 查寻该用户的所有购物车数据
            # 判断是否有 如果有count+=1
            # 如果没有直接新增
        else:
            # 用户未登录，操作cookie购物车
            # 获取cookie中所有数据
            cookie_str = request.COOKIES.get("carts")
            if cookie_str:
                # 解密
                carts_dict = CookieSecret.loads(cookie_str)
            else:
                carts_dict = {}
            # 判断是否存在
            if sku_id in carts_dict:
                # 存在则累加
                carts_dict[sku_id]["count"]+=count
            # 也可以选择更改count的变量数据
            # 不存在则新增
            else:
                carts_dict[sku_id] = {"count":count,'selected':selected}
            # 加密
            dumps_str = CookieSecret.dumps(carts_dict)
            response.set_cookie("carts",dumps_str,max_age=14*24*3600)
        return response
    # 修改购物车
    def put(self,request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)
        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在  凡是校验都用get 可以报错
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')
        user = request.user
        dumps_cart_str = ""
        if user.is_authenticated:
            carts_redis_client = get_redis_connection("carts")
            # 2.覆盖redis以前的数据
            new_data = {'count': count, 'selected': selected}
            # dumps将字典转换成字符串
            carts_redis_client.hset(user.id, sku_id, json.dumps(new_data))
        else:
            # 取出购物车数据
            cookie_str = request.COOKIES.get("carts")
            # 判断是否有  有--解码
            if cookie_str:
                carts_dict = CookieSecret.loads(cookie_str)
            else:
                carts_dict = {}
            # 整体覆盖
            carts_dict[sku_id]={'count': count, 'selected': selected}
            # 加密
            dumps_cart_str = CookieSecret.dumps(carts_dict)
            # 创建cookie
            # 构建前端的数据   由于是局部刷新  前端不能直接用sku取属性  可见都是必传项
        cart_sku = {
            'id': sku_id,
            'count': count,
            'selected': selected,
            'name': sku.name,
            'default_image_url': sku.default_image.url,
            'price': sku.price,
            'amount': sku.price * count,
        }
        response = JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        if not user.is_authenticated:
            response.set_cookie("carts",dumps_cart_str,max_age=14*24*3600)
        return response
    # 删除购物车
    def delete(self,request):
        # 接受参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        # 检验参数
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')
        user = request.user
        # 创建响应对象
        response = JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
        # 判断是否登录
        if user.is_authenticated:
            # 用户已登录，删除redis购物车
            redis_client = get_redis_connection("carts")
            redis_client.hdel(user.id,sku_id)
        else:
            # 用户未登录，删除cookie购物车
            # 获取所有数据
            cart_str = request.COOKIES.get('carts')
            # 如果有--解密--判断商品是否存在--在 del 删除---加密--返回给前端
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
                if sku_id in cart_dict:
                    del cart_dict[sku_id]
            cart_str_dumps = CookieSecret.dumps(cart_dict)

            response.set_cookie("carts",cart_str_dumps,max_age=14*24*3600)
        return response
# 全选购物车

class CartsSelectAllView(View):

    def put(self, request):
        # 接收和校验参数
        # 接收参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)

        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')
        # 判断用户是否登录
        user = request.user
        response = JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
        if user.is_authenticated:
            # 用户已登录，操作redis购物车
            carts_redis_client = get_redis_connection("carts")
            carts_dict = carts_redis_client.hgetall(user.id)
            # 遍历 ----转换bytes数据类型
            for key, value in carts_dict.items():
                # 遍历出的数据为二进制
                sku_id = int(key.decode())
                sku_dict = json.loads(carts_dict[key].decode())
                # 全选
                sku_dict["selected"]=selected

            # 重新写入数据库
                carts_redis_client.hset(user.id,sku_id,json.dumps(sku_dict))
        else:
            # 用户未登录，操作cookie购物车
            # 取出所有
            carts_str = request.COOKIES.get('carts')
            # 如果有---解密--遍历--selected---加密--cookie
            if carts_str:
                carts_dict = CookieSecret.loads(carts_str)
                for key in carts_dict:
                    carts_dict[key]["selected"] = selected
                dump_cart_str = CookieSecret.dumps(carts_dict)
                response.set_cookie("carts",dump_cart_str,max_age=14*24*3600)
        return response

# 展示商品页(简单)购物车

class CartsSimpleView(View):
    def get(self, request):
        user = request.user
        if user.is_authenticated:
            redis_client = get_redis_connection("carts")
            cart_data = redis_client.hgetall(user.id)
            # 字节转换成字典
            cart_dict = {}
            # for key,value in cart_data.items():
            #     key = int(key.decode())
            #     value = json.loads(value.decode())
            #     cart_dict[key] = value
            cart_dict = {int(key.decode()):json.loads(value.decode()) for key,value in cart_data.items()}
        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}
        skus = SKU.objects.filter(id__in=cart_dict.keys())
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image.url
            })

            # 响应json列表数据
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'cart_skus': cart_skus})



